# -*- coding: utf-8 -*-
import subprocess
import os
import sys
import platform
import time
import webbrowser
import configparser
import shutil
from tkinter import Tk, messagebox

#预先检查tqdm是否安装
try:
    from tqdm import tqdm
    from tqdm import trange
except ImportError:
    print("tqdm 未安装. 现在正在安装...")
    subprocess.check_call([sys.executable, "-m", "pip", "install", "tqdm"])
    #清屏
    if platform.system() == 'Windows':
        os.system('cls')
    elif platform.system() == 'Linux' or 'Darwin':
        os.system('clear')
    else:
        print("未知的系统，清屏失败！")
    #安装后再次调用tqdm
    from tqdm import tqdm
    from tqdm import trange

# 艺术字词典
arttext={
    'A':r"""
          _____          
         /\    \         
        /::\    \        
       /::::\    \       
      /::::::\    \      
     /:::/\:::\    \     
    /:::/__\:::\    \    
   /::::\   \:::\    \   
  /::::::\   \:::\    \    
 /:::/\:::\   \:::\    \ 
/:::/  \:::\   \:::\____\ 
\::/    \:::\  /:::/    /
 \/____/ \:::\/:::/    / 
          \::::::/    /  
           \::::/    /   
           /:::/    /    
          /:::/    /     
         /:::/    /      
        /:::/    /       
        \::/    /        
         \/____/             
    """,
    'B':r"""
          _____          
         /\    \         
        /::\    \        
       /::::\    \       
      /::::::\    \      
     /:::/\:::\    \     
    /:::/__\:::\    \    
   /::::\   \:::\    \   
  /::::::\   \:::\    \  
 /:::/\:::\   \:::\ ___\ 
/:::/__\:::\   \:::|    |
\:::\   \:::\  /:::|____|
 \:::\   \:::\/:::/    / 
  \:::\   \::::::/    /  
   \:::\   \::::/    /   
    \:::\  /:::/    /    
     \:::\/:::/    /     
      \::::::/    /      
       \::::/    /       
        \::/____/        
         ~~              
                         
    """,
    'C':r"""
          _____          
         /\    \         
        /::\    \        
       /::::\    \       
      /::::::\    \      
     /:::/\:::\    \     
    /:::/  \:::\    \    
   /:::/    \:::\    \   
  /:::/    / \:::\    \  
 /:::/    /   \:::\    \ 
/:::/____/     \:::\____\ 
\:::\    \      \::/    /
 \:::\    \      \/____/ 
  \:::\    \             
   \:::\    \            
    \:::\    \           
     \:::\    \          
      \:::\    \         
       \:::\____\        
        \::/    /        
         \/____/         
                         
    """,
    'D':r"""
          _____          
         /\    \         
        /::\    \        
       /::::\    \       
      /::::::\    \      
     /:::/\:::\    \     
    /:::/  \:::\    \    
   /:::/    \:::\    \   
  /:::/    / \:::\    \  
 /:::/    /   \:::\ ___\ 
/:::/____/     \:::|    |
\:::\    \     /:::|____|
 \:::\    \   /:::/    / 
  \:::\    \ /:::/    /  
   \:::\    /:::/    /   
    \:::\  /:::/    /    
     \:::\/:::/    /     
      \::::::/    /      
       \::::/    /       
        \::/____/        
         ~~                    
    """,
    'E':r"""
          _____          
         /\    \         
        /::\    \        
       /::::\    \       
      /::::::\    \      
     /:::/\:::\    \     
    /:::/__\:::\    \    
   /::::\   \:::\    \   
  /::::::\   \:::\    \  
 /:::/\:::\   \:::\    \ 
/:::/__\:::\   \:::\____\ 
\:::\   \:::\   \::/    /
 \:::\   \:::\   \/____/ 
  \:::\   \:::\    \     
   \:::\   \:::\____\    
    \:::\   \::/    /    
     \:::\   \/____/     
      \:::\    \         
       \:::\____\        
        \::/    /        
         \/____/         
                         
    """,
    'F':r"""
          _____          
         /\    \         
        /::\    \        
       /::::\    \       
      /::::::\    \      
     /:::/\:::\    \     
    /:::/__\:::\    \    
   /::::\   \:::\    \   
  /::::::\   \:::\    \  
 /:::/\:::\   \:::\    \ 
/:::/  \:::\   \:::\____\ 
\::/    \:::\   \::/    /
 \/____/ \:::\   \/____/ 
          \:::\    \     
           \:::\____\    
            \::/    /    
             \/____/     
    """,
    'G':r"""
          _____          
         /\    \         
        /::\    \        
       /::::\    \       
      /::::::\    \      
     /:::/\:::\    \     
    /:::/  \:::\    \    
   /:::/    \:::\    \   
  /:::/    / \:::\    \  
 /:::/    /   \:::\ ___\ 
/:::/____/  ___\:::|    |
\:::\    \ /\  /:::|____|
 \:::\    /::\ \::/    / 
  \:::\   \:::\ \/____/  
   \:::\   \:::\____\    
    \:::\  /:::/    /    
     \:::\/:::/    /     
      \::::::/    /      
       \::::/    /       
        \::/____/        
    """,
    'H':r"""
              _____          
             /\    \         
            /::\____\        
           /:::/    /        
          /:::/    /         
         /:::/    /          
        /:::/____/           
       /::::\    \           
      /::::::\    \   _____  
     /:::/\:::\    \ /\    \ 
    /:::/  \:::\    /::\____\ 
    \::/    \:::\  /:::/    /
     \/____/ \:::\/:::/    / 
              \::::::/    /  
               \::::/    /   
               /:::/    /    
              /:::/    /     
             /:::/    /      
            /:::/    /       
            \::/    /        
             \/____/                                  
    """,
    'I':r"""
          _____          
         /\    \         
        /::\    \        
        \:::\    \       
         \:::\    \      
          \:::\    \     
           \:::\    \    
           /::::\    \   
  ____    /::::::\    \  
 /\   \  /:::/\:::\    \ 
/::\   \/:::/  \:::\____\ 
\:::\  /:::/    \::/    /
 \:::\/:::/    / \/____/ 
  \::::::/    /          
   \::::/____/           
    \:::\    \           
     \:::\    \          
      \:::\    \         
       \:::\____\        
        \::/    /        
         \/____/         
                        
    """,
    'J':r"""
          _____          
         /\    \         
        /::\    \        
        \:::\    \       
         \:::\    \      
          \:::\    \     
           \:::\    \    
           /::::\    \   
  _____   /::::::\    \  
 /\    \ /:::/\:::\    \ 
/::\    /:::/  \:::\____\ 
\:::\  /:::/    \::/    /
 \:::\/:::/    / \/____/ 
  \::::::/    /          
   \::::/    /           
    \::/    /            
     \/____/             
    """,
    'K':r"""
          _____          
         /\    \         
        /::\____\        
       /:::/    /        
      /:::/    /         
     /:::/    /          
    /:::/____/           
   /::::\    \           
  /::::::\____\________  
 /:::/\:::::::::::\    \ 
/:::/  |:::::::::::\____\ 
\::/   |::|~~~|~~~~~     
 \/____|::|   |          
       |::|   |          
       |::|   |          
       |::|   |          
       |::|   |          
       |::|   |          
       \::|   |          
        \:|   |          
         \|___|          
                         
    """,
    'L':r"""
          _____  
         /\    \ 
        /::\____\ 
       /:::/    /
      /:::/    / 
     /:::/    /  
    /:::/    /   
   /:::/    /    
  /:::/    /     
 /:::/    /      
/:::/____/       
\:::\    \       
 \:::\    \      
  \:::\    \     
   \:::\    \    
    \:::\    \   
     \:::\    \  
      \:::\    \ 
       \:::\____\ 
        \::/    /
         \/____/ 
                 
    """,
    'M':r"""
          _____          
         /\    \         
        /::\____\        
       /::::|   |        
      /:::::|   |        
     /::::::|   |        
    /:::/|::|   |        
   /:::/ |::|   |        
  /:::/  |::|___|______  
 /:::/   |::::::::\    \ 
/:::/    |:::::::::\____\ 
\::/    / ~~~~~/:::/    /
 \/____/      /:::/    / 
             /:::/    /  
            /:::/    /   
           /:::/    /    
          /:::/    /     
         /:::/    /      
        /:::/    /       
        \::/    /        
         \/____/         
    """,
    'N':r"""
          _____          
         /\    \         
        /::\____\        
       /::::|   |        
      /:::::|   |        
     /::::::|   |        
    /:::/|::|   |        
   /:::/ |::|   |        
  /:::/  |::|   | _____  
 /:::/   |::|   |/\    \ 
/:: /    |::|   /::\____\ 
\::/    /|::|  /:::/    /
 \/____/ |::| /:::/    / 
         |::|/:::/    /  
         |::::::/    /   
         |:::::/    /    
         |::::/    /     
         /:::/    /      
        /:::/    /       
        \::/    /        
         \/____/         
    """,
    'O':r"""
         _______         
        /::\    \        
       /::::\    \       
      /::::::\    \      
     /::::::::\    \     
    /:::/~~\:::\    \    
   /:::/    \:::\    \   
  /:::/    / \:::\    \  
 /:::/____/   \:::\____\ 
|:::|    |     |:::|    |
|:::|____|     |:::|    |
 \:::\    \   /:::/    / 
  \:::\    \ /:::/    /  
   \:::\    /:::/    /   
    \:::\__/:::/    /    
     \::::::::/    /     
      \::::::/    /      
       \::::/    /       
        \::/____/      
    """,
    'P':r"""
          _____          
         /\    \         
        /::\    \        
       /::::\    \       
      /::::::\    \      
     /:::/\:::\    \     
    /:::/__\:::\    \    
   /::::\   \:::\    \   
  /::::::\   \:::\    \  
 /:::/\:::\   \:::\____\ 
/:::/  \:::\   \:::|    |
\::/    \:::\  /:::|____|
 \/_____/\:::\/:::/    / 
          \::::::/    /  
           \::::/    /   
            \::/____/    
             ~~          
    """,
    'Q':r"""
         _______         
        /::\    \        
       /::::\    \       
      /::::::\    \      
     /::::::::\    \     
    /:::/~~\:::\    \    
   /:::/    \:::\    \   
  /:::/    / \:::\    \  
 /:::/____/   \:::\____\ 
|:::|    |     |:::|    |
|:::|____|     |:::|____|
 \:::\   _\___/:::/    / 
  \:::\ |::| /:::/    /  
   \:::\|::|/:::/    /   
    \::::::::::/    /    
     \::::::::/    /     
      \::::::/    /      
       \::::/____/       
        |::|    |        
        |::|____|        
         ~~              
    """,
    'R':r"""
          _____          
         /\    \         
        /::\    \        
       /::::\    \       
      /::::::\    \      
     /:::/\:::\    \     
    /:::/__\:::\    \    
   /::::\   \:::\    \   
  /::::::\   \:::\    \  
 /:::/\:::\   \:::\____\ 
/:::/  \:::\   \:::|    |
\::/   |::::\  /:::|____|
 \/____|:::::\/:::/    / 
       |:::::::::/    /  
       |::|\::::/    /   
       |::| \::/____/    
       |::|  ~|          
       |::|   |          
       \::|   |          
        \:|   |          
         \|___|      
    """,
    'S':r"""
          _____          
         /\    \         
        /::\    \        
       /::::\    \       
      /::::::\    \      
     /:::/\:::\    \     
    /:::/__\:::\    \    
    \:::\   \:::\    \   
  ___\:::\   \:::\    \  
 /\   \:::\   \:::\    \ 
/::\   \:::\   \:::\____\ 
\:::\   \:::\   \::/    /
 \:::\   \:::\   \/____/ 
  \:::\   \:::\    \     
   \:::\   \:::\____\    
    \:::\  /:::/    /    
     \:::\/:::/    /     
      \::::::/    /      
       \::::/    /       
        \::/    /        
         \/____/         
    """,
    'T':r"""
      _____          
     /\    \         
    /::\    \        
    \:::\    \       
     \:::\    \      
      \:::\    \     
       \:::\    \    
       /::::\    \   
      /::::::\    \  
     /:::/\:::\    \ 
    /:::/  \:::\____\ 
   /:::/    \::/    /
  /:::/    / \/____/ 
 /:::/    /          
/:::/    /           
\::/    /            
 \/____/             
    """,
    'U':r"""
          _____          
         /\    \         
        /::\____\        
       /:::/    /        
      /:::/    /         
     /:::/    /          
    /:::/    /           
   /:::/    /            
  /:::/    /      _____  
 /:::/____/      /\    \ 
|:::|    /      /::\____\ 
|:::|____\     /:::/    /
 \:::\    \   /:::/    / 
  \:::\    \ /:::/    /  
   \:::\    /:::/    /   
    \:::\__/:::/    /    
     \::::::::/    /     
      \::::::/    /      
       \::::/    /       
        \::/____/        
         ~~              
    """,
    'V':r"""
          _____          
         /\    \         
        /::\____\        
       /:::/    /        
      /:::/    /         
     /:::/    /          
    /:::/____/           
    |::|    |            
    |::|    |     _____  
    |::|    |    /\    \ 
    |::|    |   /::\____\ 
    |::|    |  /:::/    /
    |::|    | /:::/    / 
    |::|____|/:::/    /  
    |:::::::::::/    /   
    \::::::::::/____/    
     ~~~~~~~~~~          
    """,
    'W':r"""
          _____          
         /\    \         
        /::\____\        
       /:::/    /        
      /:::/   _/___      
     /:::/   /\    \     
    /:::/   /::\____\    
   /:::/   /:::/    /    
  /:::/   /:::/   _/___  
 /:::/___/:::/   /\    \ 
|:::|   /:::/   /::\____\ 
|:::|__/:::/   /:::/    /
 \:::\/:::/   /:::/    / 
  \::::::/   /:::/    /  
   \::::/___/:::/    /   
    \:::\__/:::/    /    
     \::::::::/    /     
      \::::::/    /      
       \::::/    /       
        \::/____/        
         ~~              
    """,
    'X':r"""
        ______          
       |::|   |         
       |::|   |         
       |::|   |         
       |::|   |         
       |::|   |         
       |::|   |         
       |::|   |         
 ______|::|___|___ ____ 
|:::::::::::::::::|    |
|:::::::::::::::::|____|
 ~~~~~~|::|~~~|~~~      
       |::|   |         
       |::|   |         
       |::|   |         
       |::|   |         
       |::|   |         
       |::|   |         
       |::|___|         
        ~~              
    """,
    'Y':r"""
      _____          
     |\    \         
     |:\____\        
     |::|   |        
     |::|   |        
     |::|   |        
     |::|   |        
     |::|   |        
     |::|___|______  
     /::::::::\    \ 
    /::::::::::\____\ 
   /:::/~~~~/~~      
  /:::/    /         
 /:::/    /          
/:::/    /           
\::/    /            
 \/____/             
    """,
    'Z':r"""
          _____          
         /\    \         
        /::\    \        
        \:::\    \       
         \:::\    \      
          \:::\    \     
           \:::\    \    
            \:::\    \   
             \:::\    \  
              \:::\    \ 
_______________\:::\____\ 
\::::::::::::::::::/    /
 \::::::::::::::::/____/ 
  \:::\~~~~\~~~~~~       
   \:::\    \            
    \:::\    \           
     \:::\    \          
      \:::\    \         
       \:::\____\        
        \::/    /        
         \/____/         
    """,
    'blank':"""
            
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    """
}

#存储所用字符
# Hello OpenHarmony
text=[
    arttext['H'],arttext['E'],arttext['L'],arttext['L'],arttext['O'],arttext['blank'],arttext['O'],arttext['P'],arttext['E'],
    arttext['N'],arttext['H'],arttext['A'],arttext['R'],arttext['M'],arttext['O'],arttext['N'],arttext['Y']
    ]

def is_hidden(path):
    """检查文件是否隐藏"""
    if os.name == 'nt':  # Windows系统
        import ctypes
        attrs = ctypes.windll.kernel32.GetFileAttributesW(path)
        return attrs != -1 and attrs & 2  # FILE_ATTRIBUTE_HIDDEN
    else:  # Unix-like系统（Linux, Mac）
        return os.path.basename(path).startswith('.')

def set_hidden(path, hidden=True):
    """设置文件的隐藏属性"""
    if os.name == 'nt':  # Windows系统
        import ctypes
        attrs = ctypes.windll.kernel32.GetFileAttributesW(path)
        if hidden:
            new_attrs = attrs | 2  # 隐藏
        else:
            new_attrs = attrs & ~2  #取消隐藏
        ctypes.windll.kernel32.SetFileAttributesW(path, new_attrs)
    else:  # Unix-like系统（Linux, Mac）
        if hidden and not os.path.basename(path).startswith('.'):
            os.rename(path, f".{os.path.basename(path)}")
        elif not hidden and os.path.basename(path).startswith('.'):
            os.rename(path, path[1:])  # Remove the leading dot

def create_config(file_path):
    """创建配置文件并写入内容"""
    with open(file_path, 'w') as file:
        file.write('[Flag]\nstart = false\n')
        #文件已创建
        return "create"

def config_init(file_path):
    if not os.path.exists(file_path):
        create_config(file_path)
        set_hidden(file_path)
    elif not is_hidden(file_path):
        # 文件隐藏
        set_hidden(file_path)
    else:
        # 文件已存在且是隐藏的
        return 0

def get_desktop_path():
    """获取桌面路径"""
    if os.name == 'nt':  # Windows系统
        return os.path.join(os.environ['USERPROFILE'], 'Desktop')
    else:  # Linux/Mac系统
        return os.path.join(os.path.expanduser('~'), 'Desktop')

def update_config(file_path, start_value):
    """更新配置文件中的值"""
    config = configparser.ConfigParser()
    config.read(file_path)
    config.set('Flag', 'start', start_value)
    with open(file_path, 'w') as configfile:
        config.write(configfile)

def delete_run_py_if_exists(desktop_path):
    """如果桌面上存在run.py，则删除它"""
    run_py_path = os.path.join(desktop_path, 'run.py')
    if os.path.exists(run_py_path):
        try:
            #移除run.py
            os.remove(run_py_path)
        except Exception as e:
            print(f"无法删除文件 {run_py_path}。原因：{e}")
    else:
        #不存在
        return 0

def create_run_script(desktop_path,file_name,path):
    """在桌面创建run.py脚本"""
    run_script_content = f'''
import elevate
import configparser
import os
from tkinter import Tk, messagebox

# 请求管理员权限
elevate.elevate()

def set_hidden(path, hidden):
    """设置文件的隐藏属性"""
    if os.name == 'nt':  # Windows系统
        import ctypes
        attrs = ctypes.windll.kernel32.GetFileAttributesW(path)
        if hidden:
            new_attrs = attrs | 2  # 隐藏
        else:
            new_attrs = attrs & ~2  #取消隐藏
        ctypes.windll.kernel32.SetFileAttributesW(path, new_attrs)
    else:  # Unix-like系统（Linux, Mac）
        if hidden and not os.path.basename(path).startswith('.'):
            os.rename(path, f".{os.path.basename(path)}")
        elif not hidden and os.path.basename(path).startswith('.'):
            os.rename(path, path[1:])  # Remove the leading dot

def modify_config(file_path, section, key, value):
    """修改配置文件中的值"""
    config = configparser.ConfigParser()
    config.read(file_path)
    
    if not config.has_section(section):
        config.add_section(section)
    
    config.set(section, key, value)
    
    with open(file_path, 'w') as configfile:
        config.write(configfile)

def show_message():
    """显示系统弹窗"""
    root = Tk()
    root.withdraw()  # 隐藏主窗口
    messagebox.showinfo("彩蛋", "你启动了一个彩蛋！再次运行Hello_open.py试试吧")
    root.destroy()

if __name__ == "__main__":
    file_name = ".flag.ini"
    file_path = r'{os.path.join(os.getcwd(), file_name)}'
    show_message()  # 显示弹窗
    set_hidden(file_path,False) # 取消隐藏属性,使程序可以修改
    modify_config(file_path, 'Flag', 'start', 'true')  # 修改配置文件
    set_hidden(file_path,True) #重新隐藏
    '''
    run_script_path = os.path.join(desktop_path, 'run.py')
    with open(run_script_path,'w',encoding='utf-8') as file:
        file.write(run_script_content)
    # 确保run.py脚本可执行
    if os.name == 'nt':  # Windows系统
        os.system(f'attrib +H "{run_script_path}"')  # 隐藏文件

def delete_run_py_if_exists(desktop_path):
    """如果桌面上存在run.py，则删除它"""
    run_py_path = os.path.join(desktop_path, 'run.py')
    if os.path.exists(run_py_path):
        try:
            #移除run.py
            os.remove(run_py_path)
        except Exception as e:
            print(f"无法删除文件 {run_py_path}。原因：{e}")
    else:
        #不存在
        return 0

def website(egg):
    # 网页
    while(True):
        print("开源鸿蒙社是一个致力于推动开源技术发展的组织，于2023年6月25号正式成立，我们专注推广开源技术，提供交流、合作、培训与支持平台，鼓励成员共享代码与经验，共促开源技术发展。")
        if egg:
            print("进入官网/B站/Gitee/gitHub主页/退出/彩蛋（输入1/2/3/4/5/6）：")
        if not egg:
            print("进入官网/B站/Gitee/gitHub主页/退出（输入1/2/3/4/5）：")
        a=input()
        if a=="1":
            url = 'https://osc.tsguas.cn/'
            webbrowser.open(url)
        elif a=="2":
            url = 'https://space.bilibili.com/3546773039614687'
            webbrowser.open(url)
        elif a=="3":
            url = 'https://gitee.com/TSGU-OSC'
            webbrowser.open(url)
        elif a=="4":
            url = 'https://github.com/TSGU-OSC'
            webbrowser.open(url)
        elif a=="5":
            exit()
        elif egg:
            if a=="6":
                file_path = r'E:\program\python\Hello_open\html\index.html'
                webbrowser.open('file://' + file_path)
        else:
            print("ERROR!")

def main():
    #使用tqdm创建进度条，随进度条输出text中存储的艺术字
    for i in trange(17):
        time.sleep(0.5)
        tqdm.write(f"{text[i]}")
        #print(text[i])
    print("Hello OpenHarmony!")
    #彩蛋模块
    file_name = ".flag.ini"  # 使用点开头的文件名表示隐藏
    file_path = os.path.join(os.getcwd(), file_name)
    config_init(file_path)
    # 创建ConfigParser对象
    config = configparser.ConfigParser()
    # 读取INI文件
    config.read(file_path)
    # 获取Flag节中的start键的值
    start_value = config.get('Flag', 'start', fallback='ERROR')

    # 根据start的值进入不同状态
    if start_value.lower() == 'false':
        egg = False
        desktop_path = get_desktop_path()
        delete_run_py_if_exists(desktop_path)
        create_run_script(desktop_path,file_name,file_path)
        website(egg)
    elif start_value.lower() == 'true':
        egg = True
        website(egg)
        print("The value of 'start' is already 'true'.")
    else:
        print('ERROR')
    
if __name__ == "__main__":
    main()